package problem151;

import java.util.Stack;

//151.反转字符串中的单词
//https://leetcode.cn/problems/reverse-words-in-a-string/

class Solution {
    public String reverseWords(String s) {
        int n = s.length();
        //将每个单词存储在栈中        
        Stack<String> stack = new Stack<>();
        for(int i = 0, j = 0; j<=n; j++) {
            if(j == n || s.charAt(j) == ' ') {
                while(i < j && s.charAt(i) == ' ') {
                    i++;
                }
                if(i != j) {
                    stack.push(s.substring(i,j));
                }
                i = j;
            }
        }

        StringBuffer ret = new StringBuffer();
        while(!stack.isEmpty()) {
            ret.append(stack.pop());
            if(stack.size() > 0) {
                ret.append(" ");
            }
        }

        return ret.toString();
    }
}